package com.walker.elk.netty.heartbeat.server;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class HeartBeatServerChannelHandler extends ChannelInboundHandlerAdapter {
	
	private int lossConnectTime = 0;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + " Server :" + msg.toString());
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if(evt instanceof IdleStateEvent) {
			IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
			if(IdleState.READER_IDLE == idleStateEvent.state()) {
				System.out.println("Heart Beat Server Recevied message outTime:" + lossConnectTime++);
				if(lossConnectTime > 2) { //如果超时3次，关闭连接
					System.out.println("closed inactive connection!!!");
					ctx.channel().close();
				}
			}else {
				super.userEventTriggered(ctx, evt);
			}
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	
}
